package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.domain.Destination;
import cn.wolfcode.wolf2w.business.api.domain.Region;
import cn.wolfcode.wolf2w.business.mapper.DestinationMapper;
import cn.wolfcode.wolf2w.business.mapper.RegionMapper;
import cn.wolfcode.wolf2w.business.query.DestinationQuery;
import cn.wolfcode.wolf2w.business.service.IDestinationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 目的地Service业务层处理
 * 
 * @author Tianluhuan
 * @date 2025-09-16
 */
@Service
@Transactional
public class DestinationServiceImpl extends ServiceImpl<DestinationMapper,Destination> implements IDestinationService {

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public IPage<Destination> queryPage(DestinationQuery qo) {
        IPage<Destination> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        return lambdaQuery()
                .page(page);
    }

    @Override
    public List<Destination> querySearch(Long regionId) {
        List<Destination> list = null;
        if(regionId==-1){
            //国内
            list = lambdaQuery().eq(Destination::getParentId, 1).list();

        }else{
            Region region = regionMapper.selectById(regionId);
            String[] split = region.getRefIds().split(",");
            list = new ArrayList<>();
            for(String refId : split){
                Destination destination = baseMapper.selectById(refId);
                list.add(destination);
            }
        }
        //查询二级数据
        for(Destination destination : list){
            List<Destination> secondLevel = lambdaQuery().eq(Destination::getParentId, destination.getId())
                    .last("limit 10")
                    .list();
            destination.setChildren(secondLevel);
        }
        return list;
    }

    @Override
    public List<Destination> queryToasts(Long destId) {
        List<Destination> list = new ArrayList<>();
        createToasts(destId,list);
       // Collections.reverse(list);//返序，如果数据多这个会影响效率，可以使用回溯
        return list;
    }

    //递归调用
    private void createToasts(Long destId, List<Destination> list) {
        if (destId == null) {
            return;
        }
        Destination destination = baseMapper.selectById(destId);
        createToasts(destination.getParentId(),list);
        list.add(destination);//先查询，最后再返回数据，这个就是回溯
    }
}
